﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Tian.Common.Texts
{
    /// <summary>
    /// json与对象转换
    /// </summary>
    public class JsonObject
    {
        /// <summary>
        /// 把json文件转换成对象
        /// </summary>
        /// <typeparam name="T">对象类</typeparam>
        /// <param name="jsonPath">json文件路径</param>
        /// <returns></returns>
        public T GetObjectByJsonPath<T>(string jsonPath) where T : class
        {
            string json = File.ReadAllText(jsonPath, Encoding.Default);
            T t = JsonConvert.DeserializeObject<T>(json);
            return t;
        }
        /// <summary>
        /// 把json文件转换成对象
        /// </summary>
        /// <typeparam name="T">对象类</typeparam>
        /// <param name="jsonPath">json文件路径</param>
        /// <param name="jsonKey">json中特定key的值</param>
        /// <returns></returns>
        public T GetObjectByJsonPath<T>(string jsonPath, string jsonKey) where T : class
        {
            string json = File.ReadAllText(jsonPath, Encoding.Default);
            JObject jo = JObject.Parse(json);
            string keyValue = jo[jsonKey].ToString();
            T t = JsonConvert.DeserializeObject<T>(keyValue);
            return t;
        }

        /// <summary>
        /// 把json文件转换成对象集合
        /// </summary>
        /// <typeparam name="T">对象类</typeparam>
        /// <param name="jsonPath">json文件路径</param>
        /// <param name="jsonKey">json中特定key的值</param>
        /// <returns></returns>
        public List<T> GetObjectListByJsonPath<T>(string jsonPath, string jsonKey) where T : class
        {
            List<T> list = new List<T>();
            string json = File.ReadAllText(jsonPath, Encoding.Default);
            JObject jo = JObject.Parse(json);
            string keyValue = jo[jsonKey].ToString();
            JArray jarray = JArray.Parse(keyValue);
            for (int i = 0; i < jarray.Count; i++)
            {
                T t = JsonConvert.DeserializeObject<T>(jarray[i].ToString());
                list.Add(t);
            }
            return list;
        }
    }
}
